<template>
	<view>
		<view class="search-box">
			<uni-search-bar @input="input" :radius="100" cancel-button="none"></uni-search-bar>
		</view>
		<view class="history-box" v-if="searchResults.length === 0">
			<view class="history-title">
				<text>搜索历史</text>
				<uni-icons type="trash" size="17"></uni-icons>
			</view>
			<view class="history-list">
				<uni-tag :text="item" v-for="(item,i) in historyList" :key="i"></uni-tag>
			</view>
		</view>
		<view class="sugg-list" v-if="searchResults.length !== 0">
			<view class="sugg-item" v-for="(item,i) in searchResults" :key="i" @click="gotoDetail(item.goods_id)">
				<view class="good-name">{{item.goods_name}}</view>
				<uni-icons type="arrowright" size="16"></uni-icons>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				//延时器
				timer: null,
				//搜索关键字
				kw: '',
				//搜索结果列表
				searchResults: [],
				historyList:['a','aa','xxxx']
			};
		},
		methods: {
			input(e) {
				//清空延时器
				clearTimeout(this.timer)
				//重新启动一个延时器，并把 timerId 赋值给 this.timer
				this.timer = setTimeout(() => {
					//如果 500 毫秒内，没有触发新的输入事件，则为搜索关键词赋值
					this.kw = e
					this.getSearchList()
				}, 500)
			},
			async getSearchList() {
				if (this.ke === '') {
					this.searchResults = []
					return
				}
				const {
					data: res
				} = await uni.$http.get('api/public/v1/goods/qsearch',{query:this.kw})
				if(res.meta.status !== 200) return uni.$showMsg()
				this.searchResults = res.message
				this.saveSearchHistory()
			},
			gotoDetail(goods_id){
				uni.navigateTo({
					url:'/subPackages/goods_detail/goods_detail?goods_id=' + goods_id
				})
			},
			saveSearchHistory(){
				this.historyList.push(this.kw)
			}
		}
	}
</script>

<style lang="scss">
	.search-box {
		position: sticky;
		z-index: 999;
		top: 0%;
	}
	.sugg-list{
		padding: 0 5px;
		.sugg-item{
			font-size: 12px;
			padding: 13px 0;
			display: flex;
			align-items: center;
			justify-content: space-between;
			.good-name{
				//不允许文字换行  单行文本
				white-space: nowrap;
				//溢出部分隐藏
				overflow: hidden;
				//文本溢出后使用 ... 代替
				text-overflow: ellipsis;
				margin-right: 3px;
			}
		}
	}
	.history-box{
		padding: 0 5px;
		.history-title{
			display: flex;
			align-items: center;
			height: 40px;
			font-size: 13px;
			border-bottom: 1px solid #efefef;
		}
		.history-list{
			display: flex;
			flex-wrap: wrap;
			.uni-tag{
				margin-top: 5px;
				margin-right: 10px;
			}
		}
	}
</style>